package com.xgq.drink.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xgq.drink.entity.AttributeProduct;
import com.xgq.drink.entity.Product;
import com.xgq.drink.entity.R;
import com.xgq.drink.service.IAttributeProductService;
import com.xgq.drink.service.IProductService;
import com.xgq.drink.utils.RUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xgq
 * @since 2025-03-03
 */
@RestController
@RequestMapping("/attribute")
@Tag(name = "商品属性管理", description = "商品属性相关接口")
@RequiredArgsConstructor
public class AttributeProductController {
    private final IAttributeProductService attributeProductService;
    private final IProductService productService;

    // 根据商品ID获取属性列表
    @GetMapping("/{productId}")
    @Operation(summary = "获取商品属性列表")
    public List<AttributeProduct> getAttributesByProduct(@PathVariable Long productId) {
        List<AttributeProduct> attributes = attributeProductService.getAttributesByProduct(productId);
        // 循环打印每个属性的详细信息
        for (AttributeProduct attribute : attributes) {
            System.out.println(attribute.toString());
        }
        return attributes;
    }

    // 新增/更新属性（自动关联商品）
    // 新增属性
    @PostMapping("/creat")
    @Operation(summary = "创建商品属性")
    public R createAttribute(
            @RequestBody AttributeProduct attribute) {
        if (!productService.existsProduct(attribute.getProductId())) {
            return RUtils.fail("商品不存在");
        }
        attribute.setIsDel(0);
        // 创建时强制绑定商品ID
        if (attributeProductService.save(attribute))
            return RUtils.success("属性创建成功");
        return RUtils.fail("属性创建失败");
    }

    // 更新属性
    @PutMapping("/update")
    @Operation(summary = "更新商品属性")
    public R updateAttribute(@RequestBody AttributeProduct attribute) {
        System.out.println("属性修改");
        System.out.println(attribute);
        // 验证属性存在性
        AttributeProduct existing = attributeProductService.getById(attribute.getAttributeId());
        if (existing == null) {
            return RUtils.fail("属性不存在");
        }
        // 保持商品ID不可修改
        attribute.setProductId(existing.getProductId());
        if (attributeProductService.updateById(attribute))
            return RUtils.success("属性更新成功");
        return RUtils.fail("属性更新失败");
    }

}